<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Group extends Cachable
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    protected $fillable = [
        'name', 'copper', 'join_type',
        'join_password', 'description',
        'create_quiz_type', 'is_official',
    ];

//    protected $touches = ['users'];

    protected $hidden = [
        'join_password', 'updated_at'
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function account()
    {
        return $this
            ->hasOne(GroupUser::class)
            ->where('user_id', request()->user()->id);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function users()
    {
        return $this->belongsToMany(User::class)->withTimestamps()->select([
            'users.*', 'group_user.copper', 'group_user.join_count', 'group_user.win_count'
        ])->whereNull('group_user.deleted_at');
    }


    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function quizzes()
    {
        return $this->hasMany(Quiz::class);
    }

    /**
     * 俱乐部创建人
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function creater()
    {
        return $this
            ->belongsTo(User::class, 'user_id', 'id')
            ->select(['id', 'name', 'avatar']);
    }

    /**
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function quizzesWithCreater()
    {
        return $this->hasMany(Quiz::class)->with('creater');
    }

    /**
     * 俱乐部成员数
     *
     * @return array
     */
    public function getCountAttribute()
    {
        return [
            'users' => $this->users_count,
            'quizzes' => $this->quizzes_count,
        ];
    }
}
